#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"

namespace SocketModule
{
    using namespace LogModule;

    const int gdefaultsockfd = -1;
    const int gdefaultbacklog = 8;

    class Socket;
    using SockPtr = std::shared_ptr<Socket>;

    // 模板方法
    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual void SocketOrDie() = 0;
        virtual void SetSocketOpt() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual SockPtr Accepter(InetAddr* client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string* out) = 0;
        virtual int Send(const std::string& in) = 0;
        virtual int Fd() = 0;


        // 提供一个创建TCP套接字的固定方法
        void BuildTcpSocketMethod(int port)
        {
            SocketOrDie();
            SetSocketOpt();
            BindOrDie(port);
            ListenOrDie();
        }

        // void BuildUdpSocketMethod(int port)
        // {
        // }
    };

    // class UdpSocket : public Socket
    // {
    // };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        :_sockfd(gdefaultsockfd)
        {}
        TcpSocket(int sockfd)
        :_sockfd(sockfd)
        {}
        ~TcpSocket()
        {}

        virtual int Fd() override
        { 
            return _sockfd;
        }

        virtual void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "create socket error";
                Die(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "create socket success: " << _sockfd;
        }

        virtual void SetSocketOpt() override
        {
            int opt = 1;
            int n = ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            (void)n;
        }

        virtual bool BindOrDie(int port) override
        {
            if (_sockfd == gdefaultsockfd) return false;
            InetAddr server(port);
            int n = ::bind(_sockfd, server.NetAddr(), server.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "bind error";
                Die(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success: " << _sockfd;
            return true;
        }

        virtual bool ListenOrDie() override
        {
            if (_sockfd == gdefaultsockfd) return false;
            int n = ::listen(_sockfd, gdefaultbacklog);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "listen error";
                Die(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success: " << _sockfd;
            return true;
        }

        virtual SockPtr Accepter(InetAddr* client) override
        {
            if (!client) return nullptr;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, CONV(&peer), &len);
            if (newsockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                return nullptr;
            }
            client->SetAddr(peer, len);
            return std::make_shared<TcpSocket>(newsockfd);;
        }

        virtual void Close() override
        {
            if (_sockfd != gdefaultsockfd)
            {
                ::close(_sockfd);
            }
        }

        virtual int Recv(std::string* out) override
        {
            char buffer[1024 * 8];
            int n = ::recv(_sockfd, buffer, sizeof(buffer)-1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out = buffer;
            }
            return n;
        }

        virtual int Send(const std::string& in) override
        {
            int n = ::send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }
    private:
        int _sockfd;
    };
}

